﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AsyncCamera.Camera.media;
using Emgu.CV;
using Emgu.CV.Structure;
using Incendios0_1.tools;
using System.Drawing;
using System.Configuration;

namespace Incendios0_1.Camera.media.sinks
{
    class FileSink:MediaSink
    {
        private CwmvFile writer;
        private string currentFileName;
        //private bool open;

        private Guid sourceId;

        public FileSink(MediaSource source) : base() 
        {
            sourceId = source.GUID;
            plugIn[sourceId] = source;
            lastFrame[sourceId] = source.Frame;
            //open = false;
        }

        protected override void Tick(object sender, EventArgs e)
        {
            checkFile();
            Frame frame = plugIn[sourceId].Frame;
            lastFrame[sourceId] = frame;
            if (frame != null && frame.Image != null)
            {
                writer.AppendNewFrame(frame.Image.Bitmap);
            }

        }

        private void checkFile()
        {
            if (writer == null)
            {
                currentFileName = resolveName();
                writer = createWriter(currentFileName);
                
            }
            else
            {
                string nowName = resolveName();
                if (!nowName.Equals(currentFileName))
                {
                    writer.Close();
                    writer = createWriter(nowName);
                    currentFileName = nowName;
                }
            }
        }

        ~FileSink()
        {
            writer.Close();
        }

        private CwmvFile createWriter(string name)
        {
            //Guid g = new Guid(0x6E2A6955, 0x81DF, 0x4943, 0xBA, 0x50, 0x68, 0xA9, 0x86, 0xA7, 0x08, 0xF6);
            //WMProfile_V80_768Video wmsysprf.h Windows SDK
            Guid g = new Guid(0x74d01102,
             0xe71a,
             0x4820,
             0x8f, 0xd, 0x13, 0xd2, 0xec, 0x1e, 0x48, 0x72);
            //WMProfile_V80_BESTVBRVideo
            //Guid g = new Guid(
            // 0x48439ba,
            // 0x309c,
             //0x440e,
            // 0x9c, 0xb4, 0x3d, 0xcc, 0xa3, 0x75, 0x64, 0x23 );
            return new CwmvFile(name, ref g, (int)FPS);
        }

        private string resolveName()
        {
            string CurrTime = DateTime.Now.ToString("MM_dd_yy");
            string name = "Camera_" + AttachedCamera.cameraData.HWControlAddress.ToString();
            return ConfigurationManager.AppSettings["VideoDirectory"] +name + "_" + CurrTime + ".asf";
        }
    }
}
